#!/bin/bash

set -e

source "$(dirname "$0")/utils.sh"

REGISTRY="${CI_REGISTRY}/${CI_PROJECT_PATH}"
SHA_TAG="${CI_COMMIT_SHA}"
BRANCH_TAG="${CI_COMMIT_REF_SLUG}"

IMAGE="${REGISTRY}/gitlab-qa-gdk"

if [[ -n "${CI}" ]]; then
  OUTPUT_OPTION="--push"
else
  OUTPUT_OPTION="--load"
fi

if [[ "$BRANCH_TAG" =~ $STABLE_BRANCH_PATTERN || "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" =~ $STABLE_BRANCH_PATTERN ]]; then
  GDK_BASE_TAG_PREFIX="stable-"
fi

echoinfo "Building GDK image" "yes"

docker buildx build \
  --cache-to="type=registry,mode=max,image-manifest=true,ref=${IMAGE}/cache:${BRANCH_TAG}" \
  --cache-from="${IMAGE}/cache:${BRANCH_TAG}" \
  --cache-from="${IMAGE}/cache:master" \
  --file="qa/gdk/Dockerfile.gdk" \
  --platform=${ARCH:-amd64} \
  --build-arg "GDK_BASE_TAG_PREFIX=${GDK_BASE_TAG_PREFIX}" \
  --build-arg "GLCI_GITLAB_ASSETS_HASH_FILE=${GLCI_GITLAB_ASSETS_HASH_FILE}" \
  --build-arg "RAILS_ENV=${RAILS_ENV}" \
  --build-arg "NODE_ENV=${NODE_ENV}" \
  --build-arg="NODE_OPTIONS=${NODE_OPTIONS}" \
  --build-arg="BABEL_ENV=${BABEL_ENV}" \
  --tag="${IMAGE}:${SHA_TAG}" \
  --tag="${IMAGE}:${BRANCH_TAG}" \
  --provenance=false \
  ${OUTPUT_OPTION} \
  .

echosuccess "Built image '${REGISTRY}/gitlab-qa-gdk:${SHA_TAG}'"
